<template>
  <view class="content">
    <view class="top flex flex-between">
      <!-- <view class="address">
        <uni-icons type="location-filled" :color="baseColor"></uni-icons>
        {{ address }}
      </view> -->
	  <view class="page-title">选择商品</view>
      <view @click="goto('index/order')" class="a-link btn">
        <uni-icons type="cart-filled" color="#fff"></uni-icons>
        我的订单
      </view>
    </view>
    <view class="item-box flex flex-between">
      <view class="left-box">
        <view
          v-for="(item, index) in items"
          :key="index"
          class="left-item"
          :class="item_id == item.item_id ? 'active' : ''"
          @click="item_id = item.item_id"
        >
          {{ item.title }}
        </view>
      </view>
      <scroll-view class="right-box" scroll-y>
        <template v-for="(item, index) in skus" :key="index">
          <view class="sku-item flex flex-between">
            <image :src="item.img" class="item-pic"></image>
            <view class="item-info flex flex-column flex-between">
              <view class="item-title">{{ item.skuname }}</view>
              <view class="item-price flex flex-between">
                <view class="price-txt">￥{{ item.price }}</view>
                <uni-number-box
                  :value="getNum(item.sku_id)"
                  @change="setNum(item,$event)"
                ></uni-number-box>
              </view>
            </view>
          </view>
        </template>
      </scroll-view>
    </view>
    <view class="bottom-box flex flex-between">
      <view class="payment-info flex">
        <view class="total-price">合计：￥{{ payment }}，</view>
        <view class="total-num">共{{ buytotal }}件商品</view>
      </view>
      <view class="pay-btn" @click="showBuy()">去结算</view>
    </view>
    <uni-popup ref="orderPopup" type="bottom" :safe-area="false">
      <view class="buy-box">
        <view class="buy-title">确认订单</view>
        <view class="buy-list">
          <view
            class="buy-item flex flex-between"
            v-for="(item, index) in buyItems"
            :key="index"
          >
			<image :src="item.img" class="item-pic"></image>
            <view class="item-info  flex flex-column flex-between">
              <view class="item-title">{{ item.skuname }}</view>
              <view class="item-price flex flex-between">
                <view class="price-txt">￥{{ item.price }}</view>
                <view class="item-num">X {{item.buy_num}}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="buy-btn btn" @click="buy()">确认提交 (￥{{payment}})</view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { goto, tip } from "@/utils/utils";
import { itemLists,buyApi } from "../../api/public";
const items = ref<any[]>([]);
const item_id = ref(0);
const skus = computed(() => {
  let curItem = items.value.find(
    (item: any) => item.item_id == item_id.value
  );
  if (!curItem) return [];
  curItem.sku.forEach((item: any) => {
	  item.item_id = item_id.value;
    item.buy_num = 0;
    item.img = !item.img ? curItem.pic : item.img;
  });
  return curItem.sku;
});
const allItems = ref<any[]>([]);
const buyItems = computed(()=>{
	return allItems.value.filter((e:any)=>e.buy_num>0)
})
const payment = computed(() => {
  return parseFloat(
    buyItems.value.reduce((a: any, b: any) => a + b.price * b.buy_num, 0)
  );
});
const buytotal = computed(() => {
  return parseInt(buyItems.value.reduce((a: any, b: any) => a + b.buy_num, 0));
});
const orderPopup = ref<any>()
onLoad(() => {
	//获取商品列表
	itemLists().then((res: any) => {
	  if (res.data.length > 0) {
		//items.value = res.data.list.filter((item: any) => item.plate === "1");
		items.value = res.data;
		item_id.value = items.value[0].item_id;
	  }
	});
	allItems.value = uni.getStorageSync('carts') || []
	//登录检测
	let token = uni.getStorageSync("token");
	if (!token) {
		return tip("请先登录", () => {
			goto("index/login");
		});
	}
});
const getNum = (sku_id:number)=>{
	let row = buyItems.value.find((e:any)=>e.sku_id==sku_id)
	return row?.buy_num || 0
}
const setNum = (item: any,num:number) => {
  //购物车里是否已包含该商品
  let row = allItems.value.find((e:any)=>{
	  if(e.sku_id==item.sku_id){
		  e.buy_num = num
		  return true
	  }
	  return false
  })
  if(!row){
	  allItems.value.push({...item,...{buy_num:num}})
  }
  uni.setStorageSync('carts',allItems.value)
};
const showBuy = ()=>{
	if(buyItems.value.length==0){
		return tip("请选择要购买的商品")
	}
	setTimeout(()=>{
		orderPopup.value.open()
	})
}
const buy = ()=>{
	let buy_data = buyItems.value.map((item:any)=>{
		return {
			item_id:item.item_id,
			sku_id:item.sku_id,
			num:item.buy_num,
		}
	})
	if(buy_data.length==0){
		return tip("请选择要购买的商品")
	}
	buyApi({
		form:{
			items:buy_data
		}
	}).then((res:any)=>{
		console.log(res)
		if(res.error==0){
			tip("订单提交成功",()=>{
				uni.removeStorageSync('carts')
				goto("index/order")
			})
		}
		else{
			tip(res.msg)
		}
	})
}
</script>

<style lang="scss">
.content {
  padding-top: 20rpx;
  background: #f0f0f0;
}
.top {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  .address {
    font-size: 28rpx;
    flex: 1;
    @include text-ellipsis(1);
  }
  .a-link {
    font-size: 28rpx;
    width: 200rpx;
    text-align: right;
	height:60rpx;
	margin:0;
  }
}
.item-box {
  height: calc(100vh - 200rpx);
  border-radius: 40rpx 40rpx 0 0;
  padding-top: 40rpx;
  background: #fff;
  .left-box {
    width: 240rpx;
    height: 100%;
    background: #f0f0f0;
    .left-item {
      padding:20rpx 40rpx;
      &.active {
        background: #fff;
      }
    }
  }
  .right-box {
    flex: 1;
    padding-left: 20rpx;
    padding-right: 40rpx;
    background: #fff;
    height: 100%;
    .sku-item {
      margin-bottom: 20rpx;
      .item-pic {
        width: 100rpx;
        height: 100rpx;
        border-radius: 10rpx;
        border: 1px sloid #f0f0f0;
      }
      .item-info {
        flex: 1;
        padding-left: 10rpx;
        align-items: flex-start;
        height: 100rpx;
        .item-title {
          font-size: 30rpx;
          @include text-ellipsis(2);
        }
        .item-price {
          font-size: 28rpx;
          width: 100%;
        }
      }
    }
  }
}
.bottom-box {
  height: 100rpx;
  line-height: 100rpx;
  background: #fff;
  padding: 0 20rpx;
  .payment-info {
    font-size: 28rpx;
  }
  .pay-btn {
    font-size: 28rpx;
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: $baseColor;
    color: #fff;
    border-radius: 40rpx;
  }
}
.buy-box{
	background:#fff;
	border-radius:20rpx 20rpx 0 0;
	padding:20rpx 20rpx 100rpx;
	max-height:80vh;
	overflow-y: scroll;
	.buy-title{
		font-size:32rpx;
		height:80rpx;
		line-height: 80rpx;
		border-bottom:1px solid #f1f1f1;
	}
	.buy-list{
		margin-top: 20rpx;
		.buy-item{
			margin-bottom: 20rpx;
			.item-pic {
			  width: 100rpx;
			  height: 100rpx;
			  border-radius: 10rpx;
			  border: 1px sloid #f0f0f0;
			  flex-shrink: 1;
			}
			.item-info {
			  flex: 1;
			  padding-left: 10rpx;
			  align-items: flex-start;
			  height: 100rpx;
			  .item-title {
			    font-size: 30rpx;
			    @include text-ellipsis(2);
			  }
			  .item-price {
			    font-size: 28rpx;
			    width: 100%;
			  }
			}
		}
	}
	.buy-btn{
		position:fixed;
		bottom:0;
		left:0;
		height:80rpx;
	}
}
</style>
